package com.zlw.framework.web.handler;

import com.zlw.framework.web.mvc.Controller;
import com.zlw.framework.web.mvc.RequestMapping;
import com.zlw.framework.web.mvc.RequestParam;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName HandlerManager
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2020/1/28  21:58
 * @Version 1.0
 */

public class HandlerManager {

    public static List<MappingHandler> mappingHandlers = new ArrayList<>();

    public static void resolveMappingHandler(List<Class<?>> classList) {
        //把带有 controller 注解的类 调出来
        for (Class<?> cls : classList) {
            if (cls.isAnnotationPresent(Controller.class)) {
                parseHandlerFromController(cls);
            }
        }

    }


    private static void parseHandlerFromController(Class<?> cls) {
        //通过反射  获取这个 类所有的方法
        Method[] methods = cls.getDeclaredMethods();
        //遍历 方法 找到 requestMapping 注解的方法
        for (Method method : methods) {
            if (!method.isAnnotationPresent(RequestMapping.class)) {
                continue;
            }
            String uri = method.getDeclaredAnnotation(RequestMapping.class).value();
            List<String> paramNameList = new ArrayList<>();
            System.out.println("uri --> "+uri);

            for (Parameter parameter:method.getParameters()){
                if (parameter.isAnnotationPresent(RequestParam.class)){
                    paramNameList.add(parameter.getDeclaredAnnotation(RequestParam.class).value());
                }
            }

            String[] params = paramNameList.toArray(new String[paramNameList.size()]);

            //
            MappingHandler mappingHandler = new MappingHandler(uri,method,cls,params);

            //在 dispatchServlet 的 service方法  里面 进行使用
            HandlerManager.mappingHandlers.add(mappingHandler);

        }


    }

}
